<?php 
session_start();
require_once ("class/m_return.php");

	$m = new M_Return();
	$CreateUser=$_SESSION['username'] ;
	
	if (isset($_POST['m'])  &&  $_POST['m']!=""){
		if ($_POST['m']== 'detail'){
			if(isset($_POST['id']) && $_POST['id']!=""){ 
				$id=$_POST['id'];
				//$id=1;
				$result_main =$m->ViewHeader($id);
				$result_detail=$m->getViewDataDetail($id);
				
				$rows=$result_detail->RecordCount();
				$h="";
				if ($rows>0){
					while($row = $result_detail->FetchRow()){
						$h.="<tr>".getProductTableDetail($row)."</tr>"; 
					}
				}
				$re=array('header'=>json_encode($result_main),
						'html'=>$h,
						'rows'=>$rows
						);
						
				echo json_encode($re);
			}else{
				echo "Errro";
			}
		}else if ($_POST['m']=='running'){
				$no=$m->getRunning();
				echo "RE_".$_SESSION['branchcode'].date( "ymd" ).str_repeat('0', 3-strlen($no) ).$no;
				 
		//******************************
		//****   Edit/ Add  Product Detail
		//******************************			
		}else   if ($_POST['m']== 'p_detail'){
			if(isset($_POST['id']) && $_POST['id']!=""){ 
				$id=$_POST['id'];
				$amt=$_POST['amt'];
				$type=$_POST['type'];
				//$id=1;
				$Amount = $m->checkRemainProduct($id , $_SESSION['bid']);
				
				if($Amount >= $amt){
					$row=$m->getProductDetail($id,$amt,$type);
					$html ="<tr>".getProductTableDetail($row)."</tr>"; 
					$result=1;
				}	else  {
					$html="Input Return amount more than Remain amount (".$Amount.")";
					$result=0;
				}
				$arr = array('result'=>$result,
							'html'=>$html);
				echo json_encode( $arr );
			}else{
				echo "Errro";
			}
			
		//******************************
		//****       Add
		//******************************					
		}else if ($_POST['m']== 'add'){
			$ar= $_POST['var'];
			
			$ar["CreatedBy"]=$CreateUser;
			$ar["CreatedDate"]=date( "Y/m/d H:i:s" );
			$ar["Branch"]=$_SESSION['bid'];
			$id=$m->InsertData($ar);
		 
			$list=$ar['Detail'];
			$sql="Insert Into tb_return_product_detail (ReturnID, Product, Amounts_s, ReturnType_s) values ";
			$sqlDetail = "";
			
			 foreach ($list as $key => $val) {
			//	print_r($list[$key]. ' ');
				list($amt, $type) = split('/', $list[$key]);
				//	print_r($amt.",".$type);
				$sqlDetail.=",(".$id.",".$key.",".$amt.",".$type." ) ";
			 }
			//remove first comma
			$sqlDetail = substr($sqlDetail,1);
			//Excute
			$m->Excute($sql.$sqlDetail);					 
		//print_r($sql.$sqlDetail);
			echo "<tr>".getTable($m->ViewHeader($id),$_POST['rows']+1)."</tr>"; 


		//******************************
		//****       Edit
		//******************************					
		}else if ($_POST['m']=='edit'){
			if (isset($_POST['var'])){
				$ar=$_POST['var'];
				$flag=isset($ar);
				$id=$_POST['id'];
				$ar["Branch"]=$_SESSION['bid'];
				$ar["UpdatedBy"]=$CreateUser;
				$ar["UpdatedDate"]=date( "Y/m/d H:i:s" );
				
				$list=$ar['Detail'];
				
				$sqlScript="select * from tb_return_product where ID='".$id."'";
			
				// Insert data
				$m->updateData($sqlScript, $ar);
				
				// clear data
				$m->delDataDetail( $id );
				
				$sql="Insert Into tb_return_product_detail (ReturnID, Product, Amounts_s, ReturnType_s) values ";
							
				foreach ($list as $key => $val) {
					list($amt, $type) = split('/', $list[$key]);
					//	print_r($amt.",".$type);
					$sqlDetail.=",(".$id.",".$key.",".$amt.",".$type." ) ";
				}
				//remove first comma
				$sqlDetail = substr($sqlDetail,1);
				//Excute
				$m->Excute($sql.$sqlDetail);	
			
				echo  getTable($m->ViewHeader($id),$_POST['rows']);
			}
		}else if ($_POST['m']=='cp'){
			echo json_encode( $m->getProductList($_SESSION['bid']));
			//echo  $m->getProductList($_SESSION['bid']);
			
		//******************************
		//****       Delete
		//******************************					
		}else if ($_POST['m']=='del'){
			if(isset($_POST['var'])){
				$o=$_POST['var'];
				$m->delData($o["id"] ,$CreateUser) ;
			}
 			
	
		//******************************
		//****       Search
		//******************************
		}else if ($_POST['m']== 'search'){
			$code=$_POST['code'];
			
			if ($_SESSION['branchtype'] ==0)
				$branchid = $_SESSION['bid'] ;
			else 
				$branchid=$_POST['branchid'];
				
			$returndatefrom=$_POST['receivedatefrom'];
			$returndateto=$_POST['receivedateto'];
			$status=$_POST['status'];
			
			$page=$_POST['page'];
			
			$page=isset($page)?$page:1;
			
			$result=$m->getData($code,$branchid,$returndatefrom,$returndateto,$status,$page, $_SESSION['branchtype'] ) ;
			$rows=$m->getRowCount();
			$i=1 + (($page-1) * $m->getListPage());
			$html="";
			
			if($rows>0){
				while($row = $result->FetchRow()){
					If($i%2 <> 0){
						$html .= "<tr class=row1>";
					} else{
						$html .= "<tr>";    
					}
					$html .= getTable($row,$i)."</tr>";
					$i++;
				}
			}else{
				$html="<tr>"
					."<td colspan='9' align='center' ><img src='./images/info.gif'/><b/></td>"
					."</tr>";
			}
			//Return result , rows , page
			$ar_result=array('data'=>$html,
							'rows'=>$rows,
							'totalpage'=>$m->getTotalPage());
			echo json_encode( $ar_result );
		}
		
	//******************************
	//****       Get combo data
	//******************************			
	}else{
		if (isset($_GET['c']) && $_GET['c'] !="" ){
			echo json_encode( $m->getDataCBO($_GET['c']));
		}else if (isset($_GET['m'])&& $_GET['m'] !=""){
			echo json_encode( $m->getProductList($_SESSION['bid']));
		}
	}
	
	function getProductTableDetail($arr){
			$html= "<td align='right'>".$arr["ID"]."</td>"
					."<td align='left' style='padding-left:3px'>".$arr["ProductName"] ."</td>"
					."<td align='center'>".$arr["Unit"]."</td>"
					."<td align='right'>".number_format($arr["Amount"],0,'.',',')."</td>"
					."<td align='center'>".$arr["Type"]."</td>"
					."<td align='center'><img src='images/remove16.png' style='cursor:hand' id='btnRemove' border=0/></td>";
			return $html;
	}
 
	//for search
	function getTable($row,$i){
	global $returnScreen;
	
		if ($row["StatusID"]=='1'){
			$check="<img src='images/Send.png' class='btnSend' style='cursor:pointer'  title='Check Product' border='0'/>";
			$iStatus="<font style='font-weight:bold;color:blue'>".$row["Status"]."</font>";
			
			//Check Permission
			if ($_SESSION["permission"][$returnScreen]["Edit"]=="1")
				$edit="<img src='images/edit.png' class='btnEdit' style='cursor:pointer'  title='Edit' border='0'/>";
			else
				$edit="<img src='images/0.gif'  title=' border='0'/>";
				
			if ($_SESSION["permission"][$returnScreen]["Deleted"]=="1")
				$delete="<img src='images/remove.png' class='btnDel' style='cursor:pointer'  title='Delete' border='0'/>";
			else
				$delete="<img src='images/0.gif'  title=' border='0'/>";
				
		}else if ($row["StatusID"]=="2"){
			$iStatus="<font style='font-weight:bold;color:green'>".$row["Status"]."</font>";
			if ( $_SESSION['branchtype'] ==1){
				$check="<img src='images/check_product.png' class='btnCheck' style='cursor:pointer'  title='Check' border='0'/>";
				
				if ($_SESSION["permission"][$returnScreen]["Deleted"]=="1")
					$delete="<img src='images/remove.png' class='btnDel' style='cursor:pointer'  title='Delete' border='0'/>";
				else
					$delete="<img src='images/0.gif'  title=' border='0'/>";
			}else{
				$check="<img src='images/view.png' class='btnView' style='cursor:pointer'  title='View' border='0'/>";
				$edit="<img src='images/0.gif'  title=' border='0'/>";
				$delete="<img src='images/0.gif'  title=' border='0'/>";
			}
		}else if ($row["StatusID"]=="3"){
			$check="<img src='images/view.png' class='btnClose' style='cursor:pointer'  title='View' border='0'/>";
			$iStatus="<font style='font-weight:bold;color:#666'>".$row["Status"]."</font>";			
			$edit="<img src='images/0.gif'  title=' border='0'/>";
			$delete="<img src='images/0.gif'  title=' border='0'/>";
		}
	 
		$html .="<td align='right'>".$i."</td>";
		$html .="<td style='display:none'>".$row['ID']."</td>";
		$html .="<td style='display:none'>".$row['BranchID']."</td>";
		$html .="<td align='left'>".$row['Code']."</td>";
		
		if ($_SESSION['branchtype']==1)
			$html .="<td align='left'>".$row['BranchName']."</td>";
		
		if ($row['ReturnDate']=='' || $row['ReturnDate']=='-')
			$html .="<td align='center'>&nbsp;</td>";
		else
			$html .="<td align='center'>".$row['ReturnDate'].' by <b>'.$row['ReturnBy']."</b></td>";

		if ($row['Remark']==''){
			$remark = '&nbsp;';
		}else{
			$remark =$row['Remark'];
		}
		$html .="<td align='center'>".$iStatus."</td>";
		$html .="<td align='right'>".number_format($row['Amount'],0)."</td>";
		$html .="<td align='left'  nowrap>". $remark ."</td>";
	
		
		if ( $_SESSION['branchtype'] ==1){
			$html .="<td align='center'>".$check."</td>";
			$html .="<td align='center'>".$delete."</td>";
		}else {
			$html .="<td align='center'>".$check."</td>";
			$html .="<td align='center'>".$edit."</td>";
			$html .="<td align='center'>".$delete."</td>";
		}
		return $html;
	}

?>